package com.lingxu.module.database.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.module.database.entity.Model;
import com.lingxu.module.database.entity.ModelRun;
import com.lingxu.module.database.entity.SourceStcHis;
import com.lingxu.module.database.mapper.UseDataBaseMapper;
import com.lingxu.module.database.service.UseDataBaseService;
import com.lingxu.module.message.entity.UserMessage;
import com.lingxu.module.message.mapper.MessageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * @Title: DataBaseServiceImpl
 * @Package: com.lingxu.module.database.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/8/1 16:55
 * @Description:
 * @Version: 1.0.0
 */
@Service
public class UseDataBaseServiceImpl extends ServiceImpl<UseDataBaseMapper,SourceStcHis> implements UseDataBaseService {

    @Autowired
    private UseDataBaseMapper useDataBaseMapper;
    @Autowired
    private MessageMapper messageMapper;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${modelUrl}")
    private String modelUrl;

    //新增
    @Override
    public Result addUseDataBase(SourceStcHis stcHis) {
        try {
            //唯一性校验
            int row = useDataBaseMapper.findOnly(stcHis);
            if(row > 0){
                return Result.error("当前模型申请存在待审批记录，请勿重复提交！");
            }
            stcHis.setApprovestate("0");
            useDataBaseMapper.insert(stcHis);
            return Result.ok("操作成功");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    //查询待审批列表
    @Override
    public Result findNeedApprovalList(Integer page, Integer limit,String state,String region) {
        try {
            Page<SourceStcHis> stcHisPage = new Page<>(page,limit);
            IPage<SourceStcHis> pageInfo = useDataBaseMapper.findNeedApprovalList(stcHisPage,state,region);
            return Result.ok(pageInfo,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    //审批
    @Override
    public Result updateApproval(SourceStcHis stcHis) {
        try {
            stcHis.setApprovetime(DateUtil.formatDateTime(new Date()));
            int i = useDataBaseMapper.updateById(stcHis);
            if(i > 0){
                //调用建模系统接口通知审批情况
                String url  = modelUrl + "?id=" + stcHis.getId() + "&approveState=" + stcHis.getApprovestate() +
                        "&applyUserId=" + stcHis.getUserid() + "&modelType=" + stcHis.getModeltype() +
                        "&approveUserId=" + stcHis.getApproveuserid() + "&approveUserName=" + stcHis.getApproveusername() +
                        "&isQueryFull=" + stcHis.getIsQueryFull();
                String s = HttpUtil.get(url);
                logger.info("返回结果：" + s);

                //保存用户消息表通知审批完成
                String content = "您发起的【二级库数据使用】，使用范围：【"+stcHis.getDatarange()+"】的申请审批已通过!";
                if("2".equals(stcHis.getApprovestate())){
                    content = "您发起的【二级库数据使用】，使用范围：【"+stcHis.getDatarange()+"】的申请审批已被拒绝，" +
                            "拒绝原因：【"+stcHis.getApproveopinion()+"】，请重新发起申请";
                }
                UserMessage message = new UserMessage();
                message.setUserId(stcHis.getUserid());
                message.setRecordId(stcHis.getId());
                message.setContent(content);
                messageMapper.insert(message);

                return Result.ok("操作成功");
            }
            return Result.error("查询失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    //保存申请表数据
    @Override
    public Result saveApprovalWord(SourceStcHis stcHis) {
        try {
            int i = useDataBaseMapper.updateById(stcHis);
            if(i > 0){
                return Result.ok("操作成功");
            }
            return Result.ok("查询失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    //查询红名单查看权限待审批列表
    @Override
    public Result findApprovalRedPerson(Integer page, Integer limit, String state) {
        try {
            Page<ModelRun> model = new Page<>(page,limit);
            IPage<ModelRun> pageInfo = useDataBaseMapper.findApprovalRedPerson(model,state);
            return Result.ok(pageInfo,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    //审批红名单查看权限
    @Override
    public Result updateApprovalRedPerson(ModelRun modelRun) {
        try {
            modelRun.setApprovetime(DateUtil.formatDateTime(new Date()));
            int row = useDataBaseMapper.updateApprovalRedPerson(modelRun);
            if(row > 0){
                //保存用户消息表通知审批完成
                String content = "您发起的【模型内红名单查询查看权限】的申请审批已通过!";
                if("2".equals(modelRun.getApprovestate())){
                    content = "您发起的【模型内红名单查询查看权限】的申请审批已被拒绝，请重新发起申请";
                }
                UserMessage message = new UserMessage();
                message.setUserId(modelRun.getUserid());
                message.setRecordId(modelRun.getId());
                message.setContent(content);
                messageMapper.insert(message);
                return Result.ok("操作成功");
            }
            return Result.ok("查询失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    //保存红名单申请表
    @Override
    public Result updateApprovalRedPersonWord(ModelRun mode) {
        try {
            int row = useDataBaseMapper.updateApprovalRedPersonWord(mode);
            if(row > 0){
                return Result.ok("操作成功");
            }
            return Result.ok("查询失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result findModelApproval(Integer page, Integer limit, String state,String name) {
        try {
            Page<Model> modelPage = new Page<>(page,limit);
            IPage<Model> data = useDataBaseMapper.findModelApproval(modelPage,state,name);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("查询异常",e);
            return Result.error("查询异常");
        }
    }


    @Override
    public Result updateModelApproval(Model model) {
        try {
            //查询当前模型下的子模型id
            String childIds = useDataBaseMapper.findChildModelIds(model.getId());
            model.setApproveTime(DateUtil.formatDateTime(new Date()));
            List<String> list = Arrays.asList(childIds.split(","));
            int i = useDataBaseMapper.updateModelApproval(model,list);
            if(i > 0){
                //保存用户消息表通知审批完成
                String content = "您发起的【"+model.getName()+"】发布的申请审批已通过!";
                if("2".equals(model.getApproveState())){
                    content = "您发起的【"+model.getName()+"】的申请审批已被拒绝，请重新发起申请";
                }
                UserMessage message = new UserMessage();
                message.setUserId(model.getCreator());
                message.setRecordId(model.getId());
                message.setContent(content);
                messageMapper.insert(message);

                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result findNeedApprovalDetail(String id) {
        try {
            return Result.ok(useDataBaseMapper.findNeedApprovalDetail(id),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }
}
